package org.custom.spring.boot.datasource.filter;

import org.custom.spring.boot.datasource.entity.datasource.DynamicDatasourceSelection;
import org.custom.spring.boot.datasource.manager.DataSourceManager;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;

/**
 * 动态数据源选择拦截器
 *
 * @author 李坤
 * @date 2022/3/31 14:19
 */
public class DataSourceFilter extends OncePerRequestFilter {
    /**
     * 默认获取的头信息
     */
    private static final String HEADER = "data-source-key";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        Enumeration<String> headers = request.getHeaderNames();

        while (headers.hasMoreElements()) {
            if (Objects.equals(HEADER, headers.nextElement())) {
                //将 DynamicDatasourceSelection 设置对象设置到 DataSourceManager 中
                DataSourceManager.setDynamicDatasourceSelection(new DynamicDatasourceSelection(request.getHeader(HEADER)));
            }
        }
        // 继续向下执行
        chain.doFilter(request, response);
    }
}
